/*
 * Project: push-center-service-impl
 * 
 * File Created at 2014-10-14
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.push.service.core.tmpl.freemarker;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.mail.MailPreparationException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.Assert;

import com.greenline.push.service.core.utils.Constants;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * TemplateRender
 * 
 * @author weirui.shenwr
 * @date 2014-10-14
 * @version V1.0
 */
public class TemplateRender {

    private static Logger log = Constants.LOG_PROCESS;

    @Resource
    private Configuration configuration;

    /**
     * 获取模板
     * 
     * @param templateName
     * @return
     * @throws Exception
     */
    private Template findTmempate(String templateId) throws Exception {
        Assert.notNull(templateId, "templateId==null");
        // set local false .otherwise ,program will append _zh_cn to
        // templateId,this will call template find null-
        configuration.setLocalizedLookup(false);
        return configuration.getTemplate(templateId);
    }

    /**
     * 渲染freemarker格式模板
     * 
     * @param data
     * @return
     * @throws MailPreparationException
     */
    public String renderTemplate(String templateId, Map<String, String> data) {
        if (data == null) {
            data = new HashMap<String, String>();
        }
        try {
            Template template = findTmempate(templateId);
            log.info(String.format("{renderTemplate}使用模版[%s]渲染[%s]的数据[%s]", template.toString(),templateId,data));
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
            return content;
        } catch (Exception e) {
            log.error(e);
            throw new MailPreparationException("render template exception", e);
        }
    }
}
